﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Xml;
using System.Collections;
using System.Net.NetworkInformation;
using System.Net;

class Constants
{
    public enum ErrorType
    {
        PingError,
        Http_Get_Error
    }
    public const string SERVICE_DESC = "Program Status Check";

    public const string EVENT_LOG_NAME = "Program_Status_Check";
    public const string EVENT_LOG_TYPE = "Application";

    public const string CONFIG = "config.xml";

    public static double INTERVAL = 2700000;


    private static string proxy_ip = string.Empty;
    private static string proxy_port = string.Empty;

    private static string[] proxy_bypass_list = null;
    public const char BYPASSLIST_DELIMETER = ';';

    public static void logMessages(string msg, EventLogEntryType et)
    {
        EventLog.WriteEntry(SERVICE_DESC, msg, et);
    }

    public static List<object> loadConfig(string xmlFile)
    {

        Hashtable htUrl = new Hashtable();
        Hashtable htIp = new Hashtable();
        Hashtable htPhn = new Hashtable();
        string smsUrl = string.Empty;

        List<object> r = new List<object>();


        XmlDocument document = new XmlDocument();
        document.Load(xmlFile);

        XmlNodeList xmlUrl = document.SelectNodes("/root/urls/values");
        foreach (XmlNode itemUrl in xmlUrl)
        {
            //try
            //{
            if (itemUrl.Attributes["type"].Value.ToLower().Trim() == "ip")
            {
                htIp.Add(itemUrl.Attributes["name"].Value.Trim(), itemUrl.InnerText.Trim());
            }
            else
            {
                htUrl.Add(itemUrl.Attributes["name"].Value.Trim(), itemUrl.InnerText.Trim());
            }

            //logMessages(string.Format("URL: {0}-{1}-{2}", itemUrl.Attributes["type"].Value.Trim(),
            //itemUrl.Attributes["name"].Value.Trim(), itemUrl.InnerText.Trim()), EventLogEntryType.Information);
            //}
            //catch (Exception ex)
            //{

            //    logMessages(ex.Message, EventLogEntryType.Error);
            //}
        }
        XmlNodeList xmlPhn = document.SelectNodes("/root/pn/values");
        foreach (XmlNode itemPhn in xmlPhn)
        {
            htPhn.Add(itemPhn.InnerText.Trim(), itemPhn.InnerText.Trim());
            //logMessages(string.Format("Phone Num: {0}-{1}", itemPhn.InnerText.Trim()
            //    , itemPhn.InnerText.Trim()), EventLogEntryType.Information);
        }

        XmlNodeList xmlSmsUrl = document.SelectNodes("/root/smsUrl");
        foreach (XmlNode itemUrl in xmlSmsUrl)
        {
            smsUrl = itemUrl.InnerText.Trim();
            //logMessages(string.Format("SMS-URL: {0}", smsUrl), EventLogEntryType.Information);
            break;
        }
        XmlNodeList xmlProxy = document.SelectNodes("/root/proxy");
        if (xmlProxy != null)
        {
            foreach (XmlNode itemProxy in xmlProxy)
            {
                proxy_ip = itemProxy.Attributes["ip"].Value.Trim();
                proxy_port = itemProxy.Attributes["port"].Value.Trim();
                string proxy_bypass_list_tmp = itemProxy.Attributes["proxy_bypass_list"].Value.Trim();
                proxy_bypass_list = proxy_bypass_list_tmp.Split(BYPASSLIST_DELIMETER);
                break;
            }
        }
        XmlNodeList xmlInterval = document.SelectNodes("/root/interval");
        if (xmlInterval != null)
        {
            foreach (XmlNode itemI in xmlInterval)
            {
                INTERVAL = double.Parse(itemI.InnerText.Trim());                
                break;
            }
        }

        r.Add(htIp);
        r.Add(htUrl);
        r.Add(htPhn);
        r.Add(smsUrl);


        return r;
    }


    public static string builErrorMessage(string url, ErrorType et)
    {
        string msg = string.Empty;
        switch (et)
        {
            case ErrorType.PingError:
                return string.Format("Ping+Error+on+{0}\n", url);                
            case ErrorType.Http_Get_Error:
                return string.Format("Http+Error+on+{0}\n", url);
            default:
                return null;
        }
    }

    public static bool ping(string host)
    {
        Ping pingSender = new Ping();
        PingOptions options = new PingOptions();        
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 120;
        try
        {
            PingReply reply = pingSender.Send(host, timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            logMessages(string.Format("{0}:{1}",host,ex.Message), EventLogEntryType.Error);
            return false;
        }
    }

    public static bool getWebPage(string url)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            if (proxy_ip != string.Empty && proxy_port != string.Empty)
            {
                WebProxy wp = new WebProxy(proxy_ip, int.Parse(proxy_port));
                wp.BypassProxyOnLocal = true;
                wp.BypassList = proxy_bypass_list;// };//{ "172.20.*.*" };
                request.Proxy=wp;
            }
            request.Timeout = 120000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();                       

            HttpStatusCode sc = response.StatusCode;
            response.Close();
            response = null;
            return sc == HttpStatusCode.OK;
        }
        catch (Exception ex)
        {
            logMessages(ex.Message, EventLogEntryType.Error);
            return false;
        }
    }

    public static void sendMessage(string ph, string msg, string smsUrl)
    {
        try
        {
            smsUrl = smsUrl.Replace("Mobileno", ph);
            smsUrl = smsUrl.Replace("message", msg);
            //msg = System.Uri.EscapeDataString(msg);
            logMessages(string.Format("Sending SMS : {0} [Msg]:{1}", ph, msg), EventLogEntryType.Error);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(smsUrl);
            request.Timeout = 120000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            response.Close();

            request = null;
            response = null;
        }
        catch (Exception ex)
        {
            logMessages(string.Format("sendMessage: {0}",ex.Message), EventLogEntryType.Error);
        }
    }
}

